<?
if(isset($mesUniqueId)) {
	$mes = $getMessage[$mesUniqueId][0];
}
?>

<div class="box">
	<div class="box-header">
		<h3 class="box-title w100">
			<i class="fa fa-envelope"></i> <?=$this->lang->line("MESSAGES")?>
			<? if(isset($mesUniqueId)) { ?>
				<p class="pull-right"><button class="btn btn-sm btn-success" type="button" data-mes="-1" data-mesInsId="<?=$mes["mesInsId"]?>" data-mesUniqueId="<?=$mes["mesUniqueId"]?>"><span class="glyphicon glyphicon-plus"></span> <?=$this->lang->line("ADD_NEW")?></button></p>
			<? } ?>
		</h3>
	</div>
	<div class="box-body direct-chat direct-chat-warning">

		<?
		if(isset($mesUniqueId) and !is_null($mesUniqueId) and isset($getMessage[$mesUniqueId])) {
			$sender = $getMessage[$mesUniqueId][count($getMessage[$mesUniqueId])-1]["mesSenderUsrId"];
			//Common::pr($getMessage[$mesUniqueId]);
		?>

		<? foreach($getMessage[$mesUniqueId] as $mes) { ?>
		<div class="direct-chat-msg <?=($mes["mesSenderUsrId"] == $sender ? "right" : "")?> ">
			<div class="direct-chat-info clearfix" style="margin-top: 10px;">
				<span class="direct-chat-name pull-<?=($mes["mesSenderUsrId"] == $sender ? "right" : "left")?>"><?=($mes["mesSenderUsrId"] == $this->session->userdata("usrId") ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$this->lang->line("ME")."&nbsp;&nbsp;&nbsp;&nbsp;" : substr($mes["senderUsrEmail"],0, strpos($mes["senderUsrEmail"], "@")+1))?></span>
				<span class="direct-chat-timestamp pull-<?=($mes["mesSenderUsrId"] == $sender ? "left" : "right")?>"><?=Common::dateFromDatabase($mes["mesCreatedate"])?></span>
			</div>
			<div class="direct-chat-img"><span class="fa fa-user fa-4x"></span></div>
			<div class="direct-chat-text">
				<?=($mes["mesSubject"] ? "<p><strong>".$mes["mesSubject"]."</strong></p>" : "")?>
				<?=$mes["mesMessage"]?>
				
				<? if($mes["mesFileName"] || $this->session->userdata("usrId") == $mes["mesSenderUsrId"]) { ?>
					<p class="text-right">
					<?=($mes["mesFileName"] ? "<a href=\"".site_url("messages/download/".$mes["mesFileName"])."\" class=\"btn btn-xs btn-default\"><span class=\"fa fa-file-o\"></span> ".$mes["mesFileNameOriginal"]."</a>" : "")?>
					<? if($this->session->userdata("usrId") == $mes["mesSenderUsrId"]) { ?>
						<button class="btn btn-default btn-xs" data-mes="<?=$mes["mesId"]?>"><span class="glyphicon glyphicon-edit"></span> <?=$this->lang->line("EDIT")?></button>
						<button class="btn btn-danger btn-xs" data-mes-delete="<?=$mes["mesId"]?>"><span class="glyphicon glyphicon-remove-circle"></span> <?=$this->lang->line("DELETE")?></button>
					<? } ?>
					</p>
				<? } ?>

			</div>
		</div>
		<? } ?>

		<?
			//Common::pr($getMessage[$mesId]);
		/*
			echo	"<ul class=\"timeline\">";
			$prev_date = "";
			foreach($getMessage[$mesUniqueId] as $mes) {
				$akt_date = substr($mes["mesCreatedate"], 0, 10);
				if($akt_date != $prev_date) {
					$prev_date = $akt_date;
					echo	"
						<!-- timeline time label -->
						<li class=\"time-label\">
							<span class=\"bg-green\">
								".$akt_date."
							</span>
						</li>
						<!-- /.timeline-label -->
							";
				}

				echo	"
						<!-- timeline item -->
						<li>
							<!-- timeline icon -->
							<i class=\"fa fa-envelope bg-blue\"></i>
							<div class=\"timeline-item\">
								<span class=\"time\"><i class=\"fa fa-clock-o\"></i> ".substr($mes["mesCreatedate"], 11)."</span>

								".($mes["mesSubject"] ? "<h3 class=\"timeline-header\">".$mes["mesSubject"]."</h3>" : "")."

								<div class=\"timeline-body\">
								
									".$mes["mesMessage"]."
									".($mes["mesFileName"] ? "<br/><a href=\"".site_url("messages/download/".$mes["mesFileName"])."\" class=\"btn btn-xs btn-primary\">".$mes["mesFileNameOriginal"]." <span class=\"glyphicon glyphicon-download-alt\"></span></a>" : "")."

								</div>

								<div class=\"timeline-footer\">
									<button class=\"btn btn-primary btn-xs\" data-mes=\"".$mes["mesId"]."\"><span class=\"glyphicon glyphicon-edit\"></span> ".$this->lang->line("EDIT")."</button>
									<button class=\"btn btn-danger btn-xs\" data-mes-delete=\"".$mes["mesId"]."\"><span class=\"glyphicon glyphicon-remove-circle\"></span> ".$this->lang->line("DELETE")."</button>
								</div>
							</div>
						</li>
						<!-- END timeline item -->
						";
			}
			echo	"</ul>";
			*/

		?>
		<script>
			$(function() {
				$('button[data-mes]').unbind('click').on('click', function(e) {
					e.preventDefault();
					$this = $(this);
					$.ajax({
						type: "POST",
						cache: false,
						data: { ID: $this.data("mes"), mesInsId: $this.data("mesinsid"), mesUniqueId: $this.data("mesuniqueid") },
						url: '<?=site_url("admin_lte/message_edit")?>',
						beforeSend: function() {
							$('#studyEditorModal .modal-title').html(($this.data('mes') == '-1' ? '<?=$this->db->escape_str($this->lang->line("ADD_NEW"))?>' : '<?=$this->lang->line("EDIT")?>') + ' ' + '<?=strtolower($this->lang->line("MESSAGE"))?>');
							$('#studyEditorModal .modal-body form').html('<?=$this->db->escape_str($this->lang->line("PLEASE_WAIT,_PROCESSING_IN_PROGRESS"))?>');
							$('#studyEditorModal').modal('toggle');
						},
						success: function (result) {
							$('#studyEditorModal button.btn-success').data('url', '<?=site_url("messages")?>');
							$('#studyEditorModal .modal-body form').html(result);
						},
						error: function (error) {}
					});
				});

				$('button[data-mes-delete]').unbind('click').on('click', function() {
					$this = $(this);
					$('#studyDeleteModal .modal-title').html('<?=$this->lang->line("DELETE")?>');
					$('#studyDeleteModal .modal-body form').html('<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_ITEM"))?>');
					$('#studyDeleteModal .modal-body form').append('<input type="hidden" name="del" value="true" /><input type="hidden" name="mesId" value="' + $this.data('mesDelete') + '" />');
					$('#studyDeleteModal button.btn-danger').data('url', '<?=site_url("messages/message_insert_update");?>');
					$('#studyDeleteModal').modal('toggle');
				});

			});
		</script>
		<?

		} else {
		?>
			<table id="messageTable" class="display table table-bordered">
				<thead>
					<tr>
						<th class="text-right w1">#</th>
						<th><?=$this->lang->line("SUBJECT")?></th>
						<th><?=$this->lang->line("MESSAGE")?></th>
						<th><?=$this->lang->line("SENDER")?></th>
						<th><?=$this->lang->line("CREATED_AT")?></th>
						<th class="w1 ws"><?=$this->lang->line("VIEW_ALL_MESSAGES")?></th>
					</tr>
				</thead>
				<tbody>
					<?php
					foreach($getMessage as $mes) {
						$cnt = count($mes);
						$unread = 0;
						foreach($mes as $m) {
							if(!$m["mesReaderUsrId"])
								$unread++;
						}
						$mes = $mes[$cnt-1];
						echo		"<tr>";
						echo			"<td class=\"vm w1 text-right\"></td>";
						echo			"<td class=\"vm\">".$mes["mesSubject"]."</td>";
						echo			"<td class=\"vm\">".$mes["mesMessage"]."</td>";
						$sender = explode("@", $mes["senderUsrEmail"]);
						echo			"<td class=\"vm\">".$sender[0]."@</td>";
						echo			"<td class=\"vm\">".$mes["mesCreatedate"]."</td>";
						echo			"<td class=\"vm w1 text-center ws\">";
						echo				"<a href=\"".site_url("admin_lte/messages/".$mes["mesUniqueId"])."\" class=\"btn btn-xs btn-primary btn-block\" data-mes=\"".$mes["mesId"]."\">".$this->lang->line("VIEW_ALL_MESSAGES")." (".$cnt.($unread ? "/".$unread." ".$this->lang->line("UNREAD") : "").") <span class=\"glyphicon glyphicon-chevron-right\"></span></a>";
						echo			"</td>";
						echo		"</tr>";
					}
					?>
				</tbody>
			</table>

			<script>
				$(document).ready( function () {

					var messageTable = $('#messageTable').DataTable({
						"language": {
							"url": "<?=MEDIA?>admin_lte/DataTables-1.10.3/localization/en.lang"
						},
						"autoWidth": false,
						"columnDefs": [{
							"searchable": false,
							"orderable": false,
							"targets": 0
						}, {
							"searchable": false,
							"orderable": false,
							"targets": -1
						}],
						"order": [[ 1, 'asc' ]],
						stateSave: true
					});

					messageTable.on('draw.dt', function () {
						messageTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
							$(cell).addClass('text-right');
							cell.innerHTML = i+1 + '.';
						});
						eventRebind();
						$('#messageTable').removeClass('hidden');
					});

					messageTable.on( 'init.dt', function () {
						$('#messageTable_length').append('<button class="btn btn-sm btn-success" style="margin-left: 20px;" data-mes="-1"><span class="glyphicon glyphicon-plus"></span> <?=$this->lang->line("ADD_NEW")?></button>');
						eventRebind();
					});

				});

				var aktImageE;

				function eventRebind() {
					$('button[data-mes]').unbind('click').on('click', function(e) {
						e.preventDefault();
						$this = $(this);
						$.ajax({
							type: "POST",
							cache: false,
							data: { ID: $this.data("mes") },
							url: '<?=site_url("admin_lte/message_edit")?>',
							beforeSend: function() {
								$('#studyEditorModal .modal-title').html(($this.data('mes') == '-1' ? '<?=$this->db->escape_str($this->lang->line("ADD_NEW"))?>' : '<?=$this->lang->line("EDIT")?>') + ' ' + '<?=strtolower($this->lang->line("MESSAGE"))?>');
								$('#studyEditorModal .modal-body form').html('<?=$this->db->escape_str($this->lang->line("PLEASE_WAIT,_PROCESSING_IN_PROGRESS"))?>');
								$('#studyEditorModal').modal('toggle');
							},
							success: function (result) {
								$('#studyEditorModal button.btn-success').data('url', '<?=site_url("admin_lte/message_insert_update")?>');
								$('#studyEditorModal .modal-body form').html(result);
							},
							error: function (error) {}
						});
					});

				}

			</script>

		<? } ?>

	</div>
</div>